import { IPSAppDEMobWFDynaActionView, IPSDEForm } from '@ibiz/dynamic-model-api';
import { AppDEViewController } from './app-de-view-controller';
import { AppViewEvents, IMobWFDynaActionViewController } from '../../../interface';
import { ModelTool } from '../../../util';

export class MobWFDynaActionViewController extends AppDEViewController implements IMobWFDynaActionViewController {
  /**
   * @description 移动端动态工作流操作视图实例
   * @type {IPSAppDEMobWFDynaActionView}
   * @memberof MobWFDynaActionViewController
   */
  public viewInstance!: IPSAppDEMobWFDynaActionView;

  /**
   * @description 表单实例
   * @type {IPSDEForm}
   * @memberof MobWFDynaActionViewController
   */
  public editFormInstance!: IPSDEForm;

  /**
   * @description 初始化挂载集合
   * @memberof MobWFDynaActionViewController
   */
  public initMountedMap() {
    this.mountedMap.set('self', false);
  }

  /**
   * @description 视图挂载
   * @memberof MobWFDynaActionViewController
   */
  public viewMounted() {
    super.viewMounted();
    if (this.viewParam && this.viewParam.actionForm) {
      this.computeActivedForm(this.viewParam.actionForm);
    } else {
      this.computeActivedForm(null);
    }
    setTimeout(() => {
      const Environment = App.getEnvironment();
      if (Environment && Environment.isPreviewMode) {
        return;
      }
      this.viewState.next({
        tag: this.editFormInstance.name,
        action: 'autoload',
        data: { srfkey: this.context[this.appDeCodeName?.toLowerCase()] },
      });
    }, 0);
  }

  /**
   * @description 计算激活表单
   * @param {*} inputForm
   * @memberof MobWFDynaActionViewController
   */
  public computeActivedForm(inputForm: any) {
    if (!inputForm) {
      this.editFormInstance = ModelTool.findPSControlByName('form', this.viewInstance.getPSControls());
    } else {
      this.editFormInstance = ModelTool.findPSControlByName(
        `wfform_${inputForm.toLowerCase()}`,
        this.viewInstance.getPSControls(),
      );
    }
  }

  /**
   * @description 确认
   * @memberof MobWFDynaActionViewController
   */
  public async handleOk() {
    let xData: any = this.ctrlRefsMap.get('form');
    if (xData) {
      if (xData.formValidateStatus instanceof Function) {
        if (!await xData.formValidateStatus()) {
          App.getNoticeService().error('表单值校验错误');
          return;
        }
      }
      let preFormData: any = xData.getData();
      let nextFormData: any = xData.transformData(preFormData);
      Object.assign(preFormData, nextFormData);
      this.viewEvent(AppViewEvents.DATA_CHANGE, [preFormData])
      this.viewEvent(AppViewEvents.CLOSE, {});
    }
  }

  /**
   * @description 取消
   * @memberof MobWFDynaActionViewController
   */
  public handleCancel() {
    this.viewEvent(AppViewEvents.CLOSE, {});
  }
}
